<template>
  <!-- 头部导航栏 -->
  <div class="header">
    <van-nav-bar
      title="标题"
      @click-left="$router.push('/search')"
      @click-right="$router.push('/login')"
    >
      <template #left>
        <van-icon name="search" size="28" color="#fff" />
      </template>
      <template #right>
        <span class="login">
          登录 | 注册
        </span>
      </template>
    </van-nav-bar>
  </div>

  <!-- 主体内容 -->
  <van-pull-refresh class="home-container" v-model="refreshLoading" @refresh="onRefresh" success-text="刷新成功">
    <!-- 分类模块 -->
    <HomeCategory :category="categoryList" />
    <!-- 附近商家 -->
    <!-- 顶部标题 -->
    <div class="nearby">
      <van-icon name="wap-nav" />
      <span class="title">附近商家</span>
    </div>
    <!-- 商家组件 -->
    <!-- 商家列表 -->
    <van-list
      v-model:loading="loading"
      :finished="finished"
      finished-text="没有更多了"
      v-model:error="error"
      error-text="请求失败，点击重新加载"
      @load="onLoad"
    >
      <HomeStore :storeList="storeList"/>
    </van-list>
  </van-pull-refresh>

</template>

<script setup>
import { defineComponent, onMounted, ref, reactive } from 'vue'
import { getCatagory, getStore } from '@/api/home'
import HomeCategory from './components/home-category.vue'
import HomeStore from './components/home-store.vue'
// 组件命名
defineComponent({
  name: 'HomeIndex'
})

// 获取分类数据
const categoryList = ref([])
onMounted(() => {
  getCatagory().then(data => {
    categoryList.value = data
  })
})

// 下拉刷新
const refreshLoading = ref(false)
const onRefresh = () => {
  refreshLoading.value = false
  storeList.value = []
  pageObj.page = 1
  finished.value = false
  loading.value = true
  onLoad()
}

// 获取附近商铺数据
const storeList = ref([])
const loading = ref(false)
const finished = ref(false)
const error = ref(false)
const pageObj = reactive({
  page: 1,
  limit: 10
})
const onLoad = async () => {
  try {
    const data = await getStore(pageObj.page, pageObj.limit)
    storeList.value.push(...data)
    loading.value = false

    if (data.length) {
      pageObj.page++
    } else {
      finished.value = true
    }
  } catch (err) {
    loading.value = false
    error.value = true
    console.log(err)
  }
}
</script>

<style scoped lang="less">
.header {
  position: fixed;
  left: 0;
  top: 0;
  height: 90px;
  width: 100%;
  z-index: 999;
  :deep(.van-nav-bar__content) {
    background-color: #0a92e7;
  }

  :deep(.van-nav-bar__title) {
    color: #fff;
    font-size: 38px;
    font-weight: 500;
  }

  .login {
    color: #fff;
    font-size: 32px;
  }
}

.home-container {
  margin: 90px 0 100px 0;
  padding-bottom: 100px;
  .nearby {
    padding: 0px 20px 0px;
    background-color: #fff;
    .van-icon-wap-nav {
      color: #999;
      font-size: 32px;
    }
    .title {
      margin-left: 6px;
      color: #999;
      font-size: 28px;
      line-height: 40px;
    }
  }
}
</style>
